package cn.bbstone.pisces2.ui.views;

import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;

import cn.bbstone.pisces2.cmm.UIConst;
import cn.bbstone.pisces2.model.FileListItem;

public class FileListView {
//	private final static Logger log = LoggerFactory.getLogger(FileListView.class);
	private Text searchText = null;
	private TableViewer viewer;
	private FileListItemFilter filter = new FileListItemFilter();

	// We use icons
	private static Image CHECKED = null;// Activator.getImageDescriptor("icons/checked.gif").createImage();
	private static Image UNCHECKED = null;// Activator.getImageDescriptor("icons/unchecked.gif").createImage();

	public FileListView(Shell shell) {
		CHECKED = new Image(shell.getDisplay(), getClass().getResourceAsStream(UIConst.ICON_CHECKED));
		UNCHECKED = new Image(shell.getDisplay(), getClass().getResourceAsStream(UIConst.ICON_UNCHECKED));
	}

	public TableViewer renderUI(Composite parent) {
		GridLayout layout = new GridLayout(2, false);
		parent.setLayout(layout);
		Label searchLabel = new Label(parent, SWT.NONE);
		searchLabel.setText(Messages.FileListView_search);
		searchText = new Text(parent, SWT.BORDER | SWT.SEARCH);
		searchText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
		createViewer(parent);

		// Set the sorter for the table
//        comparator = new MyViewerComparator();
//        viewer.setComparator(comparator);

		// TODO change to press Enter key trigger search will has better performance
		// New to support the search
		searchText.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent ke) {
//				log.info("keyCode: {}", ke.keyCode);
				// Enter keyCode = 13 // && (searchText.getText() != null && searchText.getText().trim().length() > 0)
				if (ke.keyCode == 13) { // when clear searchText, search all records
					filter.setSearchText(searchText.getText());
					viewer.refresh();
				}
			}
		});
		// demo test
//        filter = new PersonFilter();
//        viewer.addFilter(filter);
		//
		filter = new FileListItemFilter();
		viewer.addFilter(filter);

		return viewer;
	}

	public void setFocus() {
		searchText.setFocus();
//		viewer.getControl().setFocus();
	}

	public void dispose() {
		if (CHECKED != null)
			CHECKED.dispose();
		if (UNCHECKED != null)
			UNCHECKED.dispose();
	}

	public void setInput(Object input) {
		viewer.setInput(input);
	}

	public void refresh() {
		viewer.refresh();
	}

	// -------------------------------------------------- render UI ---
	private void createViewer(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
		createColumns(parent, viewer);
		final Table table = viewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		viewer.setContentProvider(new ArrayContentProvider());
		// Get the content for the viewer, setInput will call getElements in the
		// contentProvider
//			viewer.setInput(ModelProvider.INSTANCE.getPersons());

		// TODO load data in another job
//			viewer.setInput(fileListService.findAll());

		// make the selection available to other views
//			getSite().setSelectionProvider(viewer);

		// Set the sorter for the table

		// Layout the viewer
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		viewer.getControl().setLayoutData(gridData);
	}

	// This will create the columns for the table
	private void createColumns(final Composite parent, final TableViewer viewer) {
		String[] titles = { Messages.FileListView_tb_seqNo, Messages.FileListView_tb_fileCat, Messages.FileListView_tb_rpath, Messages.FileListView_tb_isDelivery };
		int[] bounds = { 60, 60, 800, 80 };

		// First column is for the File NO.
		TableViewerColumn col = createTableViewerFixedColumn(titles[0], bounds[0], 0);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				FileListItem item = (FileListItem) element;
				return String.valueOf(item.getFileNo());
			}
		});

		// Second column is for the File Category
		col = createTableViewerFixedColumn(titles[1], bounds[1], 1);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				FileListItem item = (FileListItem) element;
				return item.getFileCat();
			}
		});

		// now the File Relative Path
		col = createTableViewerColumn(titles[2], bounds[2], 2);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				FileListItem item = (FileListItem) element;
				return item.getRpath();
			}
		});

		// now the status delivered
		col = createTableViewerFixedColumn(titles[3], bounds[3], 3);
		col.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				return null;
			}

			@Override
			public Image getImage(Object element) {
				if (((FileListItem) element).isDelivered()) {
					return CHECKED;
				} else {
					return UNCHECKED;
				}
			}
		});

	}

	private TableViewerColumn createTableViewerFixedColumn(String title, int bound, final int colNumber) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(title);
		column.setWidth(bound);
		column.setResizable(true);
		column.setMoveable(true);
		column.setAlignment(SWT.CENTER);
		return viewerColumn;
	}

	private TableViewerColumn createTableViewerColumn(String title, int bound, final int colNumber) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(title);
		column.setWidth(bound);
		column.setResizable(true);
		column.setMoveable(true);
		column.setAlignment(SWT.LEFT);
		return viewerColumn;
	}

	private class FileListItemFilter extends ViewerFilter {

		private String searchString;

		public void setSearchText(String s) {
			// ensure that the value can be used for matching
			this.searchString = ".*" + s + ".*"; //$NON-NLS-1$ //$NON-NLS-2$
		}

		@Override
		public boolean select(Viewer viewer, Object parentElement, Object element) {
			if (this.searchString == null || this.searchString.length() == 0) {
				return true;
			}
			FileListItem item = (FileListItem) element;
			if (String.valueOf(item.getFileNo()).matches(searchString)) {
				return true;
			}
			if (item.getFileCat().matches(searchString)) {
				return true;
			}
			if (item.getRpath().matches(searchString)) {
				return true;
			}

			return false;
		}

	}

}
